package app.goods.info.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;

public class HttpClientUtils {
//	private static final Logger LOGGER = LogManager.getLogger(HttpClientUtils.class);
	private static OkHttpClient client;
	private static String timestamp = "1662443299";

	public static void buildBasicAuthClient(final String name, final String password) {
		client = new OkHttpClient.Builder().callTimeout(420, TimeUnit.SECONDS)
				.sslSocketFactory(getSSLSocketFactory(), getTrustManager()).hostnameVerifier(getHostnameVerifier())
				.authenticator(new Authenticator() {
					@Override
					public Request authenticate(Route route, Response response) throws IOException {
						String credential = Credentials.basic(name, password);
						return response.request().newBuilder().header("Authorization", credential).build();
					}
				}).build();
	}

	public static OkHttpClient buildClient() {
		if (client == null) {
			client = new OkHttpClient.Builder().callTimeout(420, TimeUnit.SECONDS).readTimeout(420, TimeUnit.SECONDS)
					.connectTimeout(420, TimeUnit.SECONDS).sslSocketFactory(getSSLSocketFactory(), getTrustManager())
					.hostnameVerifier(getHostnameVerifier()).build();
		}
		return client;
	}

	public static String post(String url, String jsonRequestBody) {
		client = buildClient();
		MediaType JSON = MediaType.parse("application/json; charset=utf-8");
		RequestBody body = RequestBody.create(jsonRequestBody, JSON);
		Headers headers = new Headers.Builder().add("Accept", "application/json")
				.add("Content-Type", "application/json; charset=utf-8").add("Accept-Encoding", "gzip")
				.add("User-Agent", "okhttp/3.11.0").add("Connection", "keep-alive").build();
		Request request = new Request.Builder().headers(headers).url(url).post(body).build();
		try (Response response = client.newCall(request).execute()) {
			String responseBody = response.body().string();
//			LOGGER.debug(responseBody);
			return responseBody;
		} catch (Exception e) {
//			LOGGER.error(request.toString());
//			LOGGER.error(e.getMessage(), e);
		}
		return "";
	}

	public static String get(String url, Map<String, String> params) {
		client = buildClient();
		String paramsValue = "";
		HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
		if (params != null) {
			for (Map.Entry<String, String> param : params.entrySet()) {
				httpBuilder.addQueryParameter(param.getKey(), param.getValue());
				paramsValue = paramsValue + param.getValue();
			}
		}
		Request request = null;
		Headers headers = new Headers.Builder().add("Accept", "application/json").add("Accept-Language", "zh")
				.add("Host", "api.mall.sq12315.com").add("Connection", "Keep-Alive")
				.add("Content-Type", "application/json;charset=UTF-8")
//				.add("Accept-Encoding", "gzip")
				.add("User-Agent", "okhttp/3.11.").build();
		request = new Request.Builder().url(httpBuilder.build()).headers(headers).get().build();

		try (Response response = client.newCall(request).execute()) {
			String responseBody = new String(response.body().bytes(), StandardCharsets.UTF_8);

//			LOGGER.debug(responseBody);
			return responseBody;
		} catch (Exception e) {
//			LOGGER.error(request.toString());
//			LOGGER.error(e.getMessage(), e);
			return "";
		}
	}

	public static String get1(String url, Map<String, String> params) {
		client = buildClient();
		String paramsValue = "";
		HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
		if (params != null) {
			for (Map.Entry<String, String> param : params.entrySet()) {
				httpBuilder.addQueryParameter(param.getKey(), param.getValue());
				paramsValue = paramsValue + param.getValue();
			}
		}
		Request request = null;
		Headers headers = new Headers.Builder().add("Accept", "application/json;charset=UTF-8")
				.add("Connection", "Keep-Alive").add("Content-Type", "application/json;charset=UTF-8")
				.add("User-Agent", "okhttp/3.11.").build();
		request = new Request.Builder().url(httpBuilder.build()).headers(headers).get().build();

		try (Response response = client.newCall(request).execute()) {
			String responseBody = new String(response.body().bytes(), StandardCharsets.UTF_8);
//			LOGGER.debug(responseBody);
			return responseBody;
		} catch (Exception e) {
//			LOGGER.error(request.toString());
//			LOGGER.error(e.getMessage(), e);
			return "";
		}
	}

	/**
	 * description 忽略https证书验证
	 *
	 * @author yanzy
	 * @version 1.0
	 * @date 2021/9/8 14:42
	 */
	public static HostnameVerifier getHostnameVerifier() {
		HostnameVerifier hostnameVerifier = new HostnameVerifier() {
			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return true;
			}
		};
		return hostnameVerifier;
	}

	/**
	 * description 忽略https证书验证 `在这里插入代码片`
	 *
	 * @author yanzy
	 * @version 1.0
	 * @date 2021/9/8 14:42
	 */
	public static SSLSocketFactory getSSLSocketFactory() {
		try {
			SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());
			return sslContext.getSocketFactory();
		} catch (Exception e) {
//			LOGGER.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * description 忽略https证书验证
	 *
	 * @return
	 * @author yanzy
	 * @version 1.0
	 * @date 2021/9/8 14:42
	 */
	private static X509TrustManager getTrustManager() {
		return new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}
		};
	}

}
